package com.imy.accessibility;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.appcompat.app.AppCompatActivity;


import com.imy.accessibility.bean.CustomNode;

import com.imy.accessibility.node.LandscapeNodeActivity;
import com.imy.accessibility.node.NodeActivity;
import com.imy.accessibility.utils.AccessibilityUtils;
import com.imy.common.event.FloatingEvent;
import com.imy.common.util.ALog;
import com.imy.common.util.UiUtil;
import com.imy.lua.LuaCore;
import com.imy.lua.helper.PointScaleHelper;
import com.imy.lua.helper.screen.ScreenHelper;
import com.imy.lua.interfaces.CallAccessibilityServiceListener;
import com.imy.lua.lib.node.UDRule;
import com.imy.lua.manger.callback.CallBackManger;
import com.imy.lua.view.floating.FloatingManger;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public abstract class NodeInfoAccessibilityService extends AccessibilityService implements CallAccessibilityServiceListener {
    //实现辅助功能
    private static final int REQ_CODE_ACT = 0x2305;
    protected Handler mMainHandler = new Handler(Looper.getMainLooper());
    public static CustomNode mNode;
    private int ori = Configuration.ORIENTATION_PORTRAIT;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        ori=newConfig.orientation;
        ALog.i("onConfigurationChanged:"+newConfig.orientation);
    }

    @Override
    public int getOrientation() {
        //判断横竖屏 configura不准确有些机型无回调
        int rotation = FloatingManger.get().getWindowManager().getDefaultDisplay().getRotation();
        ALog.i("rotation:"+rotation);
        if (rotation== Surface.ROTATION_0
        || rotation==Surface.ROTATION_180){
            return Configuration.ORIENTATION_PORTRAIT;
        }else {
            return Configuration.ORIENTATION_LANDSCAPE;
        }


    }

    @Override
    protected boolean onKeyEvent(KeyEvent event) {
        CallBackManger.get().call(CallBackManger.KEY_EVENT, event);
        return super.onKeyEvent(event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mNode = null;
        ScreenHelper.get().clear();
    }

    private List<CustomNode> nodes = new ArrayList<>();

    @Override
    public void logNode() {
        //请求录屏命令

        ScreenHelper.get().startFastScreen(new ScreenHelper.OnScreenCaptureListener() {
            @Override
            public void onSuccess(String filepath) {
                //跳转至界面//快速截屏
                pauseNodeUpdate();
                new Thread(() -> {
                    //这里开始复制节点的信息否则进入下一个界面 getRoot获取的节点已经缺失了
                    mNode = AccessibilityUtils.copyNode(getRootInActiveWindow(), null);
                    //遍历node
                    Intent intent;
                    if (getOrientation() == Configuration.ORIENTATION_PORTRAIT) {
                        intent = new Intent(getApplicationContext(), NodeActivity.class);
                    } else {
                        intent = new Intent(getApplicationContext(), LandscapeNodeActivity.class);
                    }
                    Bundle bundle = new Bundle();
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(NodeActivity.PATH_KEY, filepath);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }).start();
            }

            @Override
            public void onFail() {
                ALog.i("截图失败");
                EventBus.getDefault().post(FloatingEvent.create(FloatingEvent.ACTION_SHOW));
            }
        });
    }

    private void getNode(CustomNode mNode) {
        for (int i = 0; i < mNode.getChildCount; i++) {
            CustomNode customNode = mNode.child.get(i);
            nodes.add(customNode);
            int getChildCount = customNode.getChildCount;
            if (getChildCount > 0) {
                getNode(customNode);
            }
        }
    }

    private void pauseNodeUpdate() {
        AccessibilityServiceInfo serviceInfo = getServiceInfo();
        serviceInfo.notificationTimeout = 60 * 60 * 60 * 1000;
        setServiceInfo(serviceInfo);                //防止节点被更新
    }

    public void resumeNodeNotify() {
        AccessibilityServiceInfo serviceInfo = getServiceInfo();
        serviceInfo.notificationTimeout = 100;
        setServiceInfo(serviceInfo);
    }

    protected abstract AppCompatActivity getActivity();

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
            if (rootInActiveWindow == null) {
                return;
            }
            ALog.i("onAccessibilityEvent:" + event);
            Boolean call = (Boolean) CallBackManger.get().call(CallBackManger.WINDOWS, event);
            if (call != null && call) {
                CallBackManger.get().call(CallBackManger.WATCH, event);
            }
            //过滤名
        }
    }

    private boolean isMatch(CharSequence className) {
        List<String> watList = LuaCore.get().getWatList();
        for (int i = 0; i < watList.size(); i++) {
            String s = watList.get(i);
            if (className.toString().equals(s)) {
                return true;
            }
        }
        return false;
    }

    private List<AccessibilityNodeInfo> findNodeById(String id) {
        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
        return rootInActiveWindow.findAccessibilityNodeInfosByViewId(id);
    }

    private List<AccessibilityNodeInfo> findNodeByText(String text) {
        AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
        return rootInActiveWindow.findAccessibilityNodeInfosByText(text);
    }

    @Override
    public List<AccessibilityNodeInfo> findNode(UDRule rule) {
        List<AccessibilityNodeInfo> list = new ArrayList<>();
        if (!TextUtils.isEmpty(rule.id)) {
            list.addAll(findNodeById(rule.id));
        }
        if (!TextUtils.isEmpty(rule.text)) {
            List<AccessibilityNodeInfo> tList = new ArrayList<>();
            if (TextUtils.isEmpty(rule.id)) {
                //id为空
                AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
                List<AccessibilityNodeInfo> accessibilityNodeInfosByText = rootInActiveWindow.findAccessibilityNodeInfosByText(rule.text);
                tList.addAll(mathText(rule.text, accessibilityNodeInfosByText));
                //完全匹配
                return filterClassName(tList, rule);
            }
            for (int i = 0; i < list.size(); i++) {
                AccessibilityNodeInfo accessibilityNodeInfo = list.get(i);
                List<AccessibilityNodeInfo> accessibilityNodeInfosByText =
                        accessibilityNodeInfo.findAccessibilityNodeInfosByText(rule.text);
                tList.addAll(mathText(rule.text, accessibilityNodeInfosByText));
            }
            return filterClassName(tList, rule);
        }
        return filterClassName(list, rule);
    }

    private List<AccessibilityNodeInfo> mathText(String text, List<AccessibilityNodeInfo> accessibilityNodeInfosByText) {
        List<AccessibilityNodeInfo> list = new ArrayList<>();
        for (int i = 0; i < accessibilityNodeInfosByText.size(); i++) {
            AccessibilityNodeInfo accessibilityNodeInfo = accessibilityNodeInfosByText.get(i);
            String s = accessibilityNodeInfo.getText().toString();
            if (s.equals(text)) {
                list.add(accessibilityNodeInfo);
            }
        }
        return list;
    }

    /**
     * 匹配符合class的节点
     *
     * @param list
     * @param rule
     * @return
     */
    private List<AccessibilityNodeInfo> filterClassName(List<AccessibilityNodeInfo> list, UDRule rule) {
        if (TextUtils.isEmpty(rule.className)) {
            for (int i = 0; i < list.size(); i++) {
                AccessibilityNodeInfo accessibilityNodeInfo = list.get(i);
                ALog.i("accessibilityNodeInfo :  i" + i + "  info " + accessibilityNodeInfo);
            }
            return list;
        } else {
            List<AccessibilityNodeInfo> matchList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                AccessibilityNodeInfo accessibilityNodeInfo = list.get(i);
                String className = accessibilityNodeInfo.getClassName().toString();
                if (className.equals(rule.className)) {
                    matchList.add(accessibilityNodeInfo);
                }
            }

            return matchList;
        }
    }

}
